﻿using System;
using System.Collections.Generic;
using System.Linq;


namespace ZilLion.Core.Unities.Config
{
    public class ZilLionConfigurationManager : IAppConfigProvider
    {
        private static ZilLionConfigurationManager _zilLionConfigurationManager;

        private readonly Dictionary<int, IAppConfigProvider> _appConfigProviderCacheDictionary =
            new Dictionary<int, IAppConfigProvider>();

        private readonly int _appConfigProvidersn = 0;

        private ZilLionConfigurationManager()
        {
            RefreshAction = () =>
            {
                foreach (var appConfigProvider in _appConfigProviderCacheDictionary.Values)
                    appConfigProvider?.RefreshAction?.Invoke();
            };


            SaveAppSettingAction = (key, value) =>
            {
                foreach (var appConfigProvider in _appConfigProviderCacheDictionary.Values)
                    appConfigProvider?.SaveAppSettingAction?.Invoke(key, value);
            };
            this.RegisterConfigProvider(new DefaultAppConfigProvider());
        }

        public string GetAppSetting(string key)
        {
            if (_appConfigProviderCacheDictionary != null)
                foreach (var appConfigProvider in _appConfigProviderCacheDictionary.OrderBy(x => x.Key))
                {
                    var value = appConfigProvider.Value.GetAppSetting(key);
                    if (value.IsNotNullOrEmpty())
                        return value;
                }

            return string.Empty;
        }


        public Action RefreshAction { get; set; }

        public Action<string, string> SaveAppSettingAction { get; set; }

        /// <summary>
        ///     注册config策略
        /// </summary>
        /// <param name="appConfigProvider"></param>
        public void RegisterConfigProvider(IAppConfigProvider appConfigProvider)
        {
            var providerKey = _appConfigProvidersn + 1;
            if (!_appConfigProviderCacheDictionary.ContainsKey(providerKey))
                _appConfigProviderCacheDictionary.Add(providerKey, appConfigProvider);
        }

        public static ZilLionConfigurationManager GetInstance()
        {
            if (_zilLionConfigurationManager == null)
                _zilLionConfigurationManager = new ZilLionConfigurationManager();
            return _zilLionConfigurationManager;
        }
    }
}